package com.mz.ozy.net;


import com.google.gson.Gson;

import com.mz.ozy.WpkApp;
import com.mz.ozy.base.BaseView;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.TUtil;
import com.socks.library.KLog;

import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * @author
 * @date 2018/8/3
 * @description
 */
public abstract class MyObserver<T> implements Observer<ResponseBody> {

    private boolean isShowProgress = true;
    private BaseView view;
    private String transCode;

    public MyObserver(BaseView view) {
        this.view = view;
    }

    public MyObserver(BaseView view, boolean showProgress) {
        this.view = view;
        this.isShowProgress = showProgress;
    }

    public MyObserver setTransCode(String transCode) {
        this.transCode = transCode;
        return this;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (isShowProgress && view != null) {
            view.showLoading();
        }
    }

    @Override
    public void onNext(ResponseBody responseBody) {

        if (view != null) {
            view.dismissLoading();
            try {
                String s = responseBody.string();
                JSONObject json = new JSONObject(s);
                String respCode = json.optString("respCode");
                String respMsg = json.optString("respMsg");
                SPUtils.getInstance(WpkApp.mcx).putString(Constants.SPName.SESSION_ID, json.optString("sessionId"));

                if (respCode.equals("00000")) {
                    if (TUtil.getClass(this, 0) == null || TUtil.getClass(this, 0) == JSONObject.class) {
                        onSuccesss((T) json);
                    } else {  //转换成泛型Bean
                        onSuccesss((T) new Gson().fromJson(json.toString(), TUtil.getClass(this, 0)));
                    }
                } else if (respCode.equals("500")) { //token生效
                    view.handleFailResponse(new NetBean(Constants.APP_NOT_INIT, respMsg, transCode));
                } else {
                    view.handleFailResponse(new NetBean(respCode, respMsg, transCode));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (view != null) {
            view.dismissLoading();
            view.handleFailResponse(new NetBean(Constants.APP_SERVER_EX, ""));
        }
    }

    @Override
    public void onComplete() {
//        KLog.e("MyObserver---onComplete");
        if (isShowProgress && view != null) {
            view.dismissLoading();
        }
    }

    public abstract void onSuccesss(T t);
}
